package com.heima.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class Jwtutil {

    // TOKEN的有效期一天（S）
    private static final int TOKEN_TIME_OUT = 3_600;
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 300;

    /**
     * 创建令牌
     *
     * @param payloadMap
     * @return
     */
    public static String token(Map<String, Object> payloadMap) {
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime))  //签发时间
                .setSubject("system")  //说明
                .setIssuer("heima") //签发者信息
                .setAudience("app")  //接收用户
                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
                .signWith(SignatureAlgorithm.HS512, key()) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))  //过期时间戳
                .addClaims(payloadMap) //cla信息
                .compact();
    }

    /**
     * 获取token中的claims信息
     * @param token
     * @return
     */
    public static <T>T parse(String token) {
        return (T) Jwts.parser()
                .setSigningKey(key())
                .parseClaimsJws(token).getBody();
    }


    /**
     * 令牌校验
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            //解析Token
            Claims claims = parse(token);
            //过期时间校验
            return expire(claims);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 是否过期
     */
    public static boolean expire(Claims claims) {
        System.out.println((claims.getExpiration().getTime() - System.currentTimeMillis()));
        try {
            if ((claims.getExpiration().getTime() - System.currentTimeMillis()) > 0) {
                return true;
            }
        } catch (Exception ex) {
        }
        return false;
    }

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey key() {
        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public static void main(String[] args) throws InterruptedException {
        Map<String, Object> payload = new HashMap<String, Object>();
        payload.put("id", 999);
        payload.put("name", "wangwu");
        String token = token(payload);
        System.out.println(token);

        Map<String,Object> payloadMap = parse(token);
        System.out.println(payloadMap);

        System.out.println(verify(token));
    }
}